package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.service.IdService;
import org.apache.commons.lang3.RandomUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(version = "1.0.0")
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;


    
    @Override
    public String saveSound(Sound sound) {
        try {
            //健壮性判断
            if (sound.getUserId() == null) {
                return null;
            }

            sound.setId(ObjectId.get());    //主键id
            sound.setCreated(System.currentTimeMillis());   //创建时间
            //设置推荐用的自增长aid
            sound.setAid(idService.getAutoIncrementId("sound",sound.getId().toHexString()));

            mongoTemplate.save(sound);
            return sound.getId().toHexString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Sound getSound(Long userId) {
        if (userId == null) {
            return null;
        }
        //查询除自己以外的音频
        Query query = Query.query(Criteria.where("userId").ne(userId));
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);

        //随机
        return soundList.get(RandomUtils.nextInt(0,soundList.size()));
    }
    /**
     * 获取用户今日剩余的语音次数
     *
     * @param userId
     * @return
     */
    @Override
    public Sound getRemain(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query,Sound.class);
    }
    /**
     * 更新语音次数
     *
     * @param sound 语音次数对象
     * @return
     */
    @Override
    public Sound updateAudioTime(Sound sound) {
        if (sound == null) {
            return null;
        }
        try {
            //查询是否存在用户的语音记录
            Query query = Query.query(Criteria.where("userId").is(sound.getUserId()));
            long count = mongoTemplate.count(query, Sound.class);
            if (count > 0) {
                //存在用户记录，更新
                Update update = Update.update("remainSendTimes",sound.getRemainSendTimes())
                        .set("remainListenTimes",sound.getRemainListenTimes())
                        .set("refresh",sound.getRefresh());
                mongoTemplate.updateFirst(query, update, Sound.class);
            } else {
                //不存在记录，新增
                mongoTemplate.save(sound);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return getRemain(sound.getUserId());
    }
}
